package com.gperp.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;



/*
 * 仅供测试
 */
@Controller
public class TestController {
	
	@RequestMapping(value="hello",method=RequestMethod.GET)
	@CrossOrigin
	@ResponseBody
	public Map<String,String> hello(){
		System.out.println("GPERP启动。。。");
		Map<String,String> map = new HashMap<String,String>();
		map.put("result", "success");
		map.put("msg", "GPERP启动。。。");
		//response.setHeader("Access-Control-Allow-Origin", "*");//解决跨域问题  
		return map;
	}
	
	@RequestMapping(value="testSession",method=RequestMethod.GET)
	@CrossOrigin
	@ResponseBody
	public Map<String,String> testSession(HttpSession session){
		Map<String,String> map = new HashMap<String,String>();
		if(session.getAttribute("user")==null){
			session.setAttribute("user", "liuzihao");
			map.put("result", "没有用户");
		}else{
			map.put("result", session.getAttribute("user").toString());
		}
		return map;
	}
	
	@RequestMapping(value="testSession2",method=RequestMethod.GET)
	@CrossOrigin
	@ResponseBody
	public Map<String,String> testSession2(HttpSession session){
		Map<String,String> map = new HashMap<String,String>();
		map.put("result", session.getAttribute("user").toString());
		return map;
	}
	
	@RequestMapping(value="setCookie",method=RequestMethod.GET)
	@CrossOrigin(allowCredentials = "true")//允许跨域的域和允许发送Cookie
	@ResponseBody
	public String setCookie(HttpServletResponse response){
	    Cookie cookie = new Cookie("test","same");
	    cookie.setPath("/");
	    response.addCookie(cookie);
	    return "{result:'success2'}";
	}
	 
	@RequestMapping(value="getCookie",method=RequestMethod.GET)
	@CrossOrigin(allowCredentials = "true")
	@ResponseBody
	public Map<String,String> getCookie(HttpServletRequest request,HttpServletResponse response){
	    Cookie[] cookies = request.getCookies();
	    Map<String,String> map = new HashMap<String,String>();
	    if (cookies != null && cookies.length >0) {
	        for (Cookie cookie : cookies) {
	            map.put(cookie.getName(), cookie.getValue());
	        }
	    }
	    return map;
	}
	
	
}
